//
//  CRUserManager.m
//  CRChatRoom
//
//  Created by CuiFengshuai on 15/11/20.
//  Copyright © 2015年 SecondGroup. All rights reserved.
//

#import "CRUserManager.h"

@interface CRUserManager ()
// 对话发起者
@property (nonatomic, strong) AVIMClient *server;
// 保存对话信息的数组
@property (nonatomic, strong) NSMutableArray *talkArray;
@end


@implementation CRUserManager

// 单例
static CRUserManager *s_defaultManager = nil;

+ (CRUserManager *)defaultManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        s_defaultManager = [[self alloc] init];
    });
    return s_defaultManager;
}
// 初始化
- (instancetype)init
{
    self = [super init];
    if (self) {
        // 实例化avuser
        self.avuser = [AVUser user];
        
        // 实例化server
        self.server = [[AVIMClient alloc] init];
    }
    return self;
}

#pragma mark >>>> 懒加载

- (NSMutableArray *)talkArray {
    if (!_talkArray) {
        _talkArray = [NSMutableArray new];
    }
    return _talkArray;
}

#pragma mark >>>> 注册方法
- (void)registerWithUsername:(NSString *)username password:(NSString *)password phone:(NSString *)phone {
    
    self.avuser.username = username;
    self.avuser.password = password;
//    self.avuser.email = email;
    self.avuser.mobilePhoneNumber = phone;
    NSError *error = nil;
    
    [self.avuser signUp:&error];
    
    // 调用注册方法
//    [self.avuser signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
//        if (succeeded) { // 成功
//            success();
//        } else { // 失败
//            failure(error);
//        }
//    }];
}

#pragma mark >>>> 登录方法
- (void)loginWithUsername:(NSString *)username password:(NSString *)password success:(void(^)())success failure:(void(^)(NSError *error))failure {
    
    [AVUser logInWithUsernameInBackground:username password:password block:^(AVUser *user, NSError *error) {
        if (!user) {
            failure(error);
        } else {
            success();
        }
    }];
    
}
#pragma mark >>>> 验证手机号码方法
- (void)verifyWithMobilePhone:(NSString *)code success:(void (^)())success failure:(void (^)(NSError *error))failure {
    [AVUser verifyMobilePhone:code withBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            success();
        } else {
            failure(error);
        }
    }];
    
}


#pragma mark >>>> 获取短信验证码
- (void)requestPasswordResetWithPhoneNumber:(NSString *)phone success:(void(^)())success failure:(void(^)(NSError *error))failure {
    
    [AVUser requestPasswordResetWithPhoneNumber:phone block:^(BOOL succeeded, NSError *error) {
        
        if (succeeded) {
            success();
        } else {
            failure(error);
        }
    }];
}

#pragma mark >>>> 重置密码
- (void)resetPasswordWithSmsCode:(NSString *)code newPassword:(NSString *)newPWD success:(void(^)())success failure:(void(^)(NSError *error))failure {
    [AVUser resetPasswordWithSmsCode:code newPassword:newPWD block:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            success();
        } else {
            failure(error);
        }
    }];
    
}

- (void)updatePasswordWithOldpwd:(NSString *)oldpwd newPwd:(NSString *)newPwd success:(void(^)())success failure:(void(^)(NSError *error))failure {
    AVUser *currentUser = [AVUser currentUser];
//    [AVUser logInWithUsername:currentUser.username password:currentUser.password error:nil];
    
    [currentUser updatePassword:oldpwd newPassword:newPwd block:^(id object, NSError *error) {
        if (error) {
            failure(error);
        } else {
            success();
        }
    }];
}

#pragma mark >>>> 发送消息
- (void)sendMessageWithMyClientID:(NSString *)myClientID otherClientID:(NSString *)otherClientID Message:(NSString *)message {
    // 用自己的 ClientId 打开 client
    [self.server openWithClientId:myClientID callback:^(BOOL succeeded, NSError *error) {
        //  建立了与某某人的会话
        [self.server createConversationWithName:@"对话" clientIds:@[otherClientID] callback:^(AVIMConversation *conversation, NSError *error) {
            // 发送消息
           [conversation sendMessage:[AVIMTextMessage messageWithText:message attributes:nil] callback:^(BOOL succeeded, NSError *error) {
               
               if (succeeded) {
                   NSLog(@"发送成功");
               } else {
                   NSLog(@"发送失败----%@", error);
               }
           }];
        }];
    }];
    
}

#pragma mark >>>> 接收消息
- (void)receiveMessageWithDelegate:(id)mydelegate myClientID:(NSString *)myClientID {
    // 设置代理对象
    self.server.delegate = mydelegate;
    // 用自己的 ClientId 打开 client
    [self.server openWithClientId:myClientID callback:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            NSLog(@"接收成功");
        } else {
            NSLog(@"接收失败----%@", error);
        }
    }];
}

#pragma mark >>>> 退出登录
- (void)logoutProcedure {
    [self.server closeWithCallback:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            NSLog(@"退出成功");
        } else {
            NSLog(@"退出失败---%@", error);
        }
    }];
    // 清除缓存用户对象
    [AVUser logOut];
    // 现在的currentUser是nil了
    [AVUser currentUser];
    
}
@end
